<template>
    <view class="container">
        <image class="bg-image" src="/static/image.jpg" mode="aspectFill"></image>
        <view class="nav-bar">
            <view class="back-btn" @click="goBack">
                <image src="/static/return.png" mode="aspectFit" class="back-icon"/>
            </view>
           <text class="dictionary-name">{{ dictionaryName }}</text>
        </view>
        
       
        
        <view class="content">
            <view class="card-body">
                <!-- 学习模式选择（数量/时间） -->
                <view class="section">
                    <view class="mode-switch">
                        <view 
                            class="switch-item"
                            :class="{ active: studyMode === 'count' }"
                            @click="switchMode('count')"
                        >
                            按数量学习
                        </view>
                        <view 
                            class="switch-item"
                            :class="{ active: studyMode === 'time' }"
                            @click="switchMode('time')"
                        >
                            按时间学习
                        </view>
                    </view>
                </view>

                <!-- 学习数量选择 -->
                <view class="section" v-if="studyMode === 'count'">
                    <text class="section-title">学习数量</text>
                    <view class="option-group">
                        <view 
                            v-for="(item, index) in countOptions" 
                            :key="index"
                            class="option-item"
                            :class="{ active: selectedCount === item.value }"
                            @click="selectCount(item.value)"
                        >
                            {{ item.label }}
                        </view>
                        <input 
                            v-if="isCustomCount"
                            type="number" 
                            v-model="customCount"
                            class="custom-input"
                            placeholder="请输入数量"
                        />
                    </view>
                </view>

                <!-- 学习时间选择 -->
                <view class="section" v-if="studyMode === 'time'">
                    <text class="section-title">学习时间（分钟）</text>
                    <view class="option-group">
                        <view 
                            v-for="(item, index) in timeOptions" 
                            :key="index"
                            class="option-item"
                            :class="{ active: selectedTime === item.value }"
                            @click="selectTime(item.value)"
                        >
                            {{ item.label }}
                        </view>
                        <input 
                            v-if="isCustomTime"
                            type="number" 
                            v-model="customTime"
                            class="custom-input"
                            placeholder="请输入时间"
                        />
                    </view>
                </view>

                <!-- 学习方式选择 -->
                <view class="section">
                    <text class="section-title">学习方式</text>
                    <view class="option-group">
                        <view 
                            v-for="(item, index) in modeOptions" 
                            :key="index"
                            class="option-item"
                            :class="{ active: selectedMode === item.value }"
                            @click="selectMode(item.value)"
                        >
                            {{ item.label }}
                        </view>
                    </view>
                </view>

                <!-- 确认按钮 -->
                <button class="confirm-btn" @click="confirmPlan">确认</button>
            </view>
        </view>
    </view>
</template>

<script>
import { plan } from '@/api/user.js'

export default {
    data() {
        return {
            studyMode: 'count', // 'count' 或 'time'
            countOptions: [
                { label: '10个', value: 10 },
                { label: '20个', value: 20 },
                { label: '30个', value: 30 },
                { label: '自定义', value: 'custom' }
            ],
            timeOptions: [
                { label: '10', value: 10 },
                { label: '15', value: 15 },
                { label: '20', value: 20 },
                { label: '自定义', value: 'custom' }
            ],
            modeOptions: [
                { label: '顺序学习', value: 'order' },
                { label: '逆序学习', value: 'reverse' },
                { label: '随机学习', value: 'random' }
            ],
            selectedCount: 10,
            selectedTime: 10,
            selectedMode: 'order',
            customCount: '',
            customTime: '',
            isCustomCount: false,
            isCustomTime: false,
            dictionaryName: '',
            dictionaryId: '',
            userId: ''
        }
    },
    onLoad() {
        // 获取选中的词典信息
        const dictionary = uni.getStorageSync('selectedDictionary')
        console.log('获取到的词典信息：', dictionary)
        
        if (dictionary) {
            this.dictionaryName = dictionary.name
            this.dictionaryId = dictionary.id
            
            console.log('更新后的词典信息：', {
                name: this.dictionaryName,
                id: this.dictionaryId
            })
        } else {
            console.warn('未找到词典信息')
            uni.showToast({
                title: '未找到词典信息',
                icon: 'none'
            })
        }
        
        // 获取用户信息
        const userInfo = uni.getStorageSync('userInfo')
        if (userInfo) {
            this.userId = userInfo.user_id
        } else {
            console.warn('未找到用户信息')
        }

        // 添加调试日志
        console.log('词典ID：', this.dictionaryId)
        console.log('词典名称：', this.dictionaryName)
    },
    methods: {
        goBack() {
            uni.navigateBack()
        },
        switchMode(mode) {
            this.studyMode = mode
        },
        selectCount(value) {
            this.selectedCount = value
            this.isCustomCount = value === 'custom'
        },
        selectTime(value) {
            this.selectedTime = value
            this.isCustomTime = value === 'custom'
        },
        selectMode(value) {
            this.selectedMode = value
        },
        async confirmPlan() {
            // 详细的数据验证
            if (!this.userId) {
                uni.showToast({
                    title: '用户信息获取失败',
                    icon: 'none'
                })
                return
            }
            
            if (!this.dictionaryId) {
                uni.showToast({
                    title: '词典信息获取失败',
                    icon: 'none'
                })
                return
            }

            // 验证学习数量/时间
            if (this.studyMode === 'count') {
                if (this.isCustomCount && !this.customCount) {
                    uni.showToast({
                        title: '请输入学习数量',
                        icon: 'none'
                    })
                    return
                }
            } else if (this.studyMode === 'time') {
                if (this.isCustomTime && !this.customTime) {
                    uni.showToast({
                        title: '请输入学习时间',
                        icon: 'none'
                    })
                    return
                }
            }

            // 准备请求数据
            const planData = {
                ...(this.studyMode === 'count' ? {
                    plan_quantity: this.isCustomCount ? this.customCount : String(this.selectedCount)
                } : {
                    plan_time: this.isCustomTime ? this.customTime : String(this.selectedTime)
                }),
				dictionary_id: this.dictionaryId,
				plan_type: this.selectedMode === 'order' ? '0' :
				          this.selectedMode === 'reverse' ? '1' : '2',
                user_id: this.userId
            }

            console.log('发送的数据：', planData) // 添加日志输出

           
            try {
        const res = await plan(planData)
        console.log('计划保存响应：', res)

        if (res.code === '2000') {
            // 保存当前词典信息和计划ID
            const dictionaryInfo = {
                dictionary_id: this.dictionaryId,
                dictionary_name: this.dictionaryName,
                plan_id: res.data
            }
            console.log('保存的词典信息：', dictionaryInfo)
            
            // 保存到本地存储
            uni.setStorageSync('currentDictionary', dictionaryInfo)
            uni.setStorageSync('currentPlanId', res.data)

            // 将词典添加到我的词典列表
            let myDictionaries = uni.getStorageSync('myDictionaries') || []
            // 检查是否已存在
            if (!myDictionaries.some(dict => dict.id === this.dictionaryId)) {
                myDictionaries.push({
                    id: this.dictionaryId,
                    name: this.dictionaryName,
                    planId: res.data
                })
                uni.setStorageSync('myDictionaries', myDictionaries)
            }

            uni.showToast({
                title: '计划保存成功',
                icon: 'success'
            })
            
            setTimeout(() => {
                uni.switchTab({
                    url: '/pages/home/home'
                })
            }, 1500)
        } else {
            uni.showToast({
                title: res.msg || '保存失败',
                icon: 'none'
            })
        }
    } catch (error) {
        console.error('保存计划失败:', error)
        uni.showToast({
            title: '保存失败，请重试',
            icon: 'none'
        })
    }
}
    }
}
</script>

<style>
.container {
    position: relative;
    min-height: 100vh;
}

.bg-image {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: -1;
}

.nav-bar {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    display: flex;
    align-items: center;
    padding: 40px 20px 20px;
    z-index: 100;
}

.back-btn {
    width: 40px;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.back-icon {
    width: 24px;
    height: 24px;
}

.nav-title {
    flex: 1;
    text-align: center;
    font-size: 18px;
    font-weight: 500;
    color: #333;
    text-shadow: 0 1px 2px rgba(255, 255, 255, 0.5);
}

.content {
    padding-top: 20px;
    min-height: 100vh;
}

.card-body {
    background: rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(10px);
    border-radius: 12px;
    padding: 20px;
    margin-top: 80px;
}

/* 如果需要列表项样式 */
.info-item {
    width: 100%;
    height: 44px;
    border: 1px solid rgba(238, 238, 238, 0.5);
    border-radius: 8px;
    margin-bottom: 15px;
    padding: 0 15px;
    display: flex;
    align-items: center;
    background: rgba(255, 255, 255, 0.1);
}

.item-label {
    width: 60px;
    color: #333;
    font-size: 14px;
}

.item-value {
    flex: 1;
    color: #333;
    font-size: 14px;
    margin-left: 10px;
}

/* 如果需要按钮样式 */
.confirm-btn {
    background: rgba(107, 75, 138, 0.9);
    color: white;
    border-radius: 8px;
    height: 44px;
    line-height: 44px;
    text-align: center;
    font-size: 16px;
    width: 100%;
    margin-top: 20px;
}

.section {
    margin-bottom: 20px;
}

.section-title {
    font-size: 16px;
    color: #333;
    margin-bottom: 12px;
    font-weight: 500;
}

.option-group {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.option-item {
    padding: 8px 16px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 20px;
    font-size: 14px;
    color: #333;
    transition: all 0.3s ease;
}

.option-item.active {
    background: rgba(107, 75, 138, 0.9);
    color: white;
}

.custom-input {
    width: 100px;
    height: 35px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 20px;
    padding: 0 15px;
    font-size: 14px;
    color: #333;
}

.confirm-btn {
    background: rgba(107, 75, 138, 0.9);
    color: white;
    border-radius: 8px;
    height: 44px;
    line-height: 44px;
    text-align: center;
    font-size: 16px;
    width: 100%;
    margin-top: 30px;
}

.confirm-btn:active {
    opacity: 0.8;
}

.mode-switch {
    display: flex;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 20px;
    padding: 4px;
    margin-bottom: 20px;
}

.switch-item {
    flex: 1;
    text-align: center;
    padding: 8px 0;
    font-size: 14px;
    color: #333;
    border-radius: 16px;
    transition: all 0.3s ease;
}

.switch-item.active {
    background: rgba(107, 75, 138, 0.9);
    color: white;
}

.dictionary-info {
    padding: 20px;
    margin-top: 80px;  /* 调整位置，避免被导航栏遮挡 */
    text-align: center;
}

.dictionary-name {
    font-size: 18px;
    font-weight: 500;
	margin-left: 50px;
	
    color: #333;
    text-shadow: 0 1px 2px rgba(255, 255, 255, 0.5);
}
</style>
